package com.softright.net;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.logging.Logger;

/**
 * 
 * @author lemon
 *
 */
public class FileBody extends MutilPartBody {
	
	//   CONTENT_TYPE = "Content-Type: image/jpeg"    // 图片
	
	private static final String CONTENT_TYPE = "Content-Type: application/octet-stream";
	
	private static final Logger logger = Logger.getLogger(FileBody.class.getName());
	
	FileBody(String fieldName, File file) {
		StringBuffer sb = new StringBuffer();
		sb.append("Content-Disposition: form-data; name=\"" + fieldName + "\"");
		sb.append("; filename=\"" + file.getName() + "\"");
		sb.append("\r\n");
		sb.append(CONTENT_TYPE);
		sb.append("\r\n");
		sb.append("\r\n");
		ByteBuffer byteBuffer = null;
		int len = 0;
		FileInputStream ins;
		try {
			byte[] sb_bytes = sb.toString().getBytes();
			ins = new FileInputStream(file);
			DataInputStream dataInputStream = new DataInputStream(ins);
			len = dataInputStream.available() + sb_bytes.length;
			byteBuffer = ByteBuffer.allocate(len);
			byteBuffer.put(sb_bytes);
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = dataInputStream.read(bufferOut)) != -1) {
				byteBuffer.put(bufferOut, 0, bytes);
			}
			this.bytes = byteBuffer.array();
			length = this.bytes.length;
		} catch (FileNotFoundException e) {
			logger.severe(e.toString());
		} catch (IOException e) {
			logger.severe(e.toString());
		}
	}

	@Override
	public void put(DataOutputStream os) throws FileUploadException {
		try {
			byte[] bytes = getBytes();
			os.write(bytes, 0, bytes.length);
		} catch (IOException e) {
			throw new FileUploadException(e);
		}
	}
}
